<!-- 自动化实验-任务进程总览 -->
<template>
  <!-- 顶部搜索区 -->
  <div class="main-app" v-loading="loading">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-top: 5px; margin-bottom: 15px;">
      <el-breadcrumb-item :to="{path:'/'}">{{$t('common.nav.home')}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{$t('common.nav.automationExperiment')}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{$t('common.nav.taskOverview')}}</el-breadcrumb-item>
    </el-breadcrumb>
    <!--统计信息区域-->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover" class="box-card device-status-panal device-status-panal-bg">
          <div class="monitor-btn" @click="operation($t('common.button.realTimeMonitoring'))">
            <img src="../../../assets/icon/automation_experiment/task_overview/monitor.png" />
            <span>{{$t('common.button.realTimeMonitoring')}}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="box-card statistics-panal statistics-panal-bg-1">
          <div class="titie-bar"><span>{{$t('common.title.expStatistics')}}</span></div>
          <pieexpstatistics id="container" :data="ExpStatisticsData" style="height: 317px;"></pieexpstatistics>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="box-card statistics-panal statistics-panal-bg-2 work-statistics-panal">
          <div class="titie-bar"><span>{{$t('common.title.deviceWorkStatistics')}}</span></div>
          <div style="height: 317px;">
            <div class="title">{{$t('common.title.thisExpExpectedCompletionTime')}}</div>
            <div class="content">
              <span>{{ThisExpCompletionTime_h}}</span>
              <span>{{$t('common.title.hour')}}</span>
              <span>{{ThisExpCompletionTime_m}}</span>
              <span>{{$t('common.title.minute')}}</span>
              <span>{{ThisExpCompletionTime_s}}</span>
              <span>{{$t('common.title.second')}}</span>
            </div>
            <hr style="border: 1px solid rgba(61, 171, 175, 1);"/>
            <div class="title">{{$t('common.title.accumulateExpWorkTime')}}</div>
            <div class="content"  >
              <span>{{Accumulatework_h}}</span>
              <span>{{$t('common.title.hour')}}</span>
              <span>{{Accumulatework_m}}</span>
              <span>{{$t('common.title.minute')}}</span>
              <span>{{Accumulatework_s}}</span>
              <span>{{$t('common.title.second')}}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- Robot机器人状态监控区 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card" style="margin-top: 1%; height: 190px;">
          <div class="titie-bar"><span>{{$t('common.title.agvConditionMonitoring')}}</span></div>
          <!-- 状态信息-内容 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card shadow="hover" class="box-card status-panal" style="margin-top: 10px;">
                <div class="status-panal">
                  <div class="status-titie"><span>{{$t('common.label.currentProgramNo')}}</span></div>
                  <div class="status-value"><span>{{deviceStatusData.currentProgramNo}}</span></div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="hover" class="box-card status-panal" style="margin-top: 10px;">
                <div class="status-panal">
                  <div class="status-titie"><span>{{$t('common.label.currentStationNo')}}</span></div>
                  <div class="status-value"><span>{{deviceStatusData.currentStationNo}}</span></div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card" style="margin-top: 1%; height: 190px;">
          <div class="titie-bar"><span>{{$t('common.title.expOperation')}}</span></div>
          <div style="margin-top: 20px;">
            <el-button type="primary" plain @click="operation($t('common.button.fullLineAutomaticStart'))">{{$t('common.button.fullLineAutomaticStart')}}</el-button>
            <el-button type="primary" plain @click="operation($t('common.button.fullLineAutomaticStop'))">{{$t('common.button.fullLineAutomaticStop')}}</el-button>
            <el-button type="primary" plain @click="operation($t('common.button.automaticMode'))">{{$t('common.button.automaticMode')}}</el-button>
            <el-button type="primary" plain @click="operation($t('common.button.manualMode'))">{{$t('common.button.manualMode')}}</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 数据列表区 -->
    <el-card class="box-card" style="margin-top: 1%;">
      <div class="titie-bar"><span>{{$t('common.title.expTaskQueue')}}</span></div>
      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchParam" class="form-inline" style="margin-top: 20px;">
        <el-form-item :label="$t('common.label.expName')+':'">
          <el-input v-model="searchParam.name" clearable />
        </el-form-item>
        <el-form-item :label="$t('common.label.expNumber')+':'">
          <el-input v-model="searchParam.number" clearable />
        </el-form-item>
        <el-form-item :label="$t('common.label.expStatus')+':'">
          <el-select v-model="searchParam.status" :placeholder="$t('common.placeholder.pleaseSelect')">
            <el-option :label="$t('common.label.all')" value="10,20" />
            <el-option :label="$t('common.label.inQueue')" value="10" />
            <el-option :label="$t('common.label.inProgress')" value="20" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">{{$t('common.button.search')}}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh-right" @click="reset">{{$t('common.button.reset')}}</el-button>
        </el-form-item>
      </el-form>
      <!-- 数据表格 -->
      <div class="show-result">
        <div class="table">
          <el-table id="table" ref="multipleTable" tooltip-effect="dark" stripe style="width: 100%" :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column prop="name" :label="$t('common.label.expName')" align="center"/>
            <el-table-column prop="number" :label="$t('common.label.expNumber')" align="center"/>
            <el-table-column prop="status" :label="$t('common.label.expStatus')" width="130" align="center">
              <template slot-scope="scope">
                <el-tag style="width: 100%; text-align: center" effect="dark" :class="'bg-' + scope.row.statusColor">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="expectedWorkingHours" :label="$t('common.label.expectedWorkingHours')" align="center"/>
            <!-- <el-table-column prop="sort" :label="$t('common.label.expSort')" align="center"/> -->
            <el-table-column prop="createUserName" :label="$t('common.label.createUserName')" align="center"/>
            <el-table-column prop="createTime" :label="$t('common.label.createTime')" width="180" align="center">
              <template slot-scope="scope">
                {{ scope.row.createTime | parseDate }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.label.operate')" align="center" width="200">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button size="mini" type="warning" :disabled="scope.row.status === `${$t('common.label.inQueue')}`" @click="operation($t('common.button.stopTask'), scope.row)">{{$t('common.button.stopTask')}}</el-button>
                  <el-button size="mini" type="danger" :disabled="scope.row.status === `${$t('common.label.inProgress')}`" @click="operation($t('common.button.cancelTask'), scope.row)">{{$t('common.button.cancelTask')}}</el-button>
                </el-button-group>
              </template>
            </el-table-column>
            <el-table-column align="center" width="50">
              <template slot-scope="scope">
                <i class="el-icon-rank handle"></i>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 列表底部分页按钮 -->
        <div class="page">
          <el-pagination background layout="total, prev, pager, next, sizes"
            :total="total"
            :current-page.sync="currentPage"
            :page-sizes="[5, 10, 20, 50, 100]"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
// 引用 Sortable
import Sortable from 'sortablejs'
import { pageMixin } from "../../../mixins/index";
import {
  SetNodeData,
  GetJakaRobotStatus
} from "../../../api/device.js";
import {
  ExperimentTaskQueueList,
  UpdateExperimentRecordStstus,
  UpdateExperimentRecordSort,
} from "../../../api/record.js";
import {
  CheckExperimentQueue,
  ExperimentStatistics,
  GetThisExpectedCompletionTime,
  Accumulateworkduration,
} from "../../../api/experiment.js";
import pieexpstatistics from "./PieExpStatistics.vue";
export default {
  // 页面公共变量
  data() {
    return {
      searchParam: {
        name: "",
        number: "",
        status: "10,20"
      },                                  // 搜索条件参数
      dialogVisible: false,               // 是否隐藏提示框
      ExpStatisticsData: [],              // 实验统计数据
      // 设备运行状态数据
      deviceStatusData: {
        currentProgramNo: 0,              // 当前程序号
        currentStationNo: 0,              // 当前工位号
      },

      ThisExpCompletionTime_all: [],		  // 累计实验工作时长
      ThisExpCompletionTime_h: '00',			// 累计实验工作 时
      ThisExpCompletionTime_m: '00',      // 累计实验工作 分
      ThisExpCompletionTime_s: '00',      // 累计实验工作 秒

      Accumulatework_all: [],		          // 累计实验工作时长
      Accumulatework_h: '00',			        // 累计实验工作 时
      Accumulatework_m: '00',             // 累计实验工作 分
      Accumulatework_s: '00',             // 累计实验工作 秒

      timer: null,                        // 计时器
    };
  },
  // 页面创建完成事件
  async created() {
    this.init();

    this.timer = setInterval(async () => {
      this.init();

      // 检查实验任务队列
      await CheckExperimentQueue().then((res) => {
        if (res.success === false) {
          this.$message({ type: 'error', message: res.msg });
        }
      });
    }, 5000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    console.log('定时刷新数据计时器已清除');
  },
  // 引用组件
  components: {
    pieexpstatistics
  },
  // 数据过滤器
  filters: {
    // 转换日期显示格式
    parseDate(value) {
      if (value) {
        return value.replace("T", " ");
      }
    },
  },
  // 表格分页属性配置
  mixins: [pageMixin],
  // 页面相关方法
  methods: {
    // 初始化加载事件
    async init() {
      //this.loading = true;        // 打开加载框

      // 获取统计数据
      await ExperimentStatistics({}).then(result => {
        if (result.success === true) {
          this.ExpStatisticsData = result;
        }
      });

      // 获取当前实验预计完成时长
      await GetThisExpectedCompletionTime({}).then(result => {
        if (result.success === true) {
          this.ThisExpCompletionTime_all = result.data.split(',');
          this.ThisExpCompletionTime_h = this.ThisExpCompletionTime_all[0];
          this.ThisExpCompletionTime_m = this.ThisExpCompletionTime_all[1];
          this.ThisExpCompletionTime_s = this.ThisExpCompletionTime_all[2];
        }
      });

      // 获取累计实验工作时长
      await Accumulateworkduration({}).then(result => {
        if (result.success === true) {
          this.Accumulatework_all = result.data.split(',');
          this.Accumulatework_h = this.Accumulatework_all[0];
          this.Accumulatework_m = this.Accumulatework_all[1];
          this.Accumulatework_s = this.Accumulatework_all[2];
        }
      });

      // 获取Robot机器人状态详情数据
      await GetJakaRobotStatus().then(res => {
        if (res.success === true) {
          // 设置数据源
          this.deviceStatusData = res.data;
        }
      });

      // 获取列表数据
      const { data, count } = await ExperimentTaskQueueList({
        page: this.currentPage,
        limit: this.pageSize,
        Name: this.searchParam.name,
        Number: this.searchParam.number,
        Status: this.searchParam.status,
      });
      this.tableData = data;      // 设置表格数据源
      // 转换表格数据源部分字段显示
      this.tableData.forEach((item) => {
        switch (item.status) {
          case "10":
            item.status = this.$t('common.label.inQueue');
            item.statusColor = "blue";
            break;
          case "20":
            item.status = this.$t('common.label.inProgress');
            item.statusColor = "green";
            break;
          case "30":
            item.status = this.$t('common.label.completed');
            item.statusColor = "grey";
            break;
          case "40":
            item.status = this.$t('common.label.terminated');
            item.statusColor = "red";
            break;
          case "50":
            item.status = this.$t('common.label.canceled');
            item.statusColor = "yellow";
            break;
        }
        if (item.expStartTime === null) {
          item.expStartTime = '---';
        }
        if (item.expEndTime === null) {
          item.expEndTime = '---';
        }
      });
      this.total = count;         // 设置表格总数据量
      this.rowDrop();             // 挂载更改表格排序事件

      //this.loading = false;       // 关闭加载框
    },
    // 表格重置事件
    async reset() {
      this.searchParam = {
        name: "",
        number: "",
        status: "10,20"
      };
      await this.init();
    },
    // 操作功能按钮点击事件
    operation(value, row) {
      switch (value) {
        // 实景监控
        case this.$t('common.button.realTimeMonitoring'):
          this.$router.push(`/automation_experiment/monitor`);
          break;
        // 全线自动启动
        case this.$t('common.button.fullLineAutomaticStart'):
          this.fullLineAutomaticStart();
          break;
        // 全线自动停止
        case this.$t('common.button.fullLineAutomaticStop'):
          this.fullLineAutomaticStop();
          break;
        // 自动模式
        case this.$t('common.button.automaticMode'):
          this.automaticMode();
          break;
        // 手动模式
        case this.$t('common.button.manualMode'):
          this.manualMode();
          break;
        // 停止
        case this.$t('common.button.stopTask'):
          this.stopTask(row.id);
          break;
        // 取消任务
        case this.$t('common.button.cancelTask'):
          this.cancelTask(row.id);
          break;
      }
    },
    // 数据行更改事件
    rowDrop() {
      //const el = document.querySelector('#table .el-table__body-wrapper tbody')
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
      const sortable = new Sortable(el, {
        animation: 150,
        handle: '.handle',
        ghostClass: 'blue-background-class',
        onEnd: evt => {
          // 更改数据源数组顺序
          this.tableData.splice(evt.newIndex, 0, this.tableData.splice(evt.oldIndex, 1)[0]);
          const newArray = this.tableData.slice(0);
          newArray.forEach((value, index) => {
            value.sort = index + 1; // 序号为index+1
            this.$set(newArray, index, value);

          	this.tableData = [];
          	this.$nextTick(() => {
          	  this.tableData = newArray ? newArray : [];
          	})
          });
          this.$nextTick(() => {
            // 保存更改至数据库
            this.updateSort(this.tableData);
          })
        }
      });
    },
    // 全线自动启动
    async fullLineAutomaticStart() {
      await SetNodeData({
        SetValueData: [{
          Id: 'SiemensTCP.s1500.GeneralControl.Start',
          Type: 'bool',
          Value: '1'
        }]
      }).then(res => {
        if (res.success === true) {
          this.$message({type: 'success', message: res.msg});
        } else {
          this.$message({type: 'error', message: res.msg});
        }
      });
    },
    // 全线自动停止
    async fullLineAutomaticStop() {
      await SetNodeData({
        SetValueData: [{
          Id: 'SiemensTCP.s1500.GeneralControl.End',
          Type: 'bool',
          Value: '1'
        }]
      }).then(res => {
        if (res.success === true) {
          this.$message({type: 'success', message: res.msg});
        } else {
          this.$message({type: 'error', message: res.msg});
        }
      });
    },
    // 自动模式
    async automaticMode() {
      await SetNodeData({
        SetValueData: [{
          Id: 'SiemensTCP.s1500.GeneralControl.OperateMode',
          Type: 'bool',
          Value: '1'
        }]
      }).then(res => {
        if (res.success === true) {
          this.$message({type: 'success', message: res.msg});
        } else {
          this.$message({type: 'error', message: res.msg});
        }
      });
    },
    // 手动模式
    async manualMode() {
      await SetNodeData({
        SetValueData: [{
          Id: 'SiemensTCP.s1500.GeneralControl.OperateMode',
          Type: 'bool',
          Value: '0'
        }]
      }).then(res => {
        if (res.success === true) {
          this.$message({type: 'success', message: res.msg});
        } else {
          this.$message({type: 'error', message: res.msg});
        }
      });
    },
    // 停止任务
    async stopTask(id) {
      this.$confirm(this.$t('common.prompt.info.isStopExp'), this.$t('common.dialog.tip'), {
        confirmButtonText: this.$t('common.dialog.confirm'),
        cancelButtonText: this.$t('common.dialog.cancel'),
      }).then(() => {
        UpdateExperimentRecordStstus({
          Id: id,
          Status: '40'
        }).then(res => {
          if (res.success === true) {
            this.$message({ type: 'success', message: this.$t('common.prompt.success.updateExpStatus') });
          } else {
            this.$message({ type: 'error', message: msg });
          }

          // 检查实验任务队列
          CheckExperimentQueue().then((res) => {
            if (res.success === false) {
              this.$message({ type: 'error', message: res.msg });
            }
          });

          this.init();
        });
      });
    },
    // 取消任务
    async cancelTask(id) {
      this.$confirm(this.$t('common.prompt.info.isCancelExp'), this.$t('common.dialog.tip'), {
        confirmButtonText: this.$t('common.dialog.confirm'),
        cancelButtonText: this.$t('common.dialog.cancel'),
      }).then(() => {
        UpdateExperimentRecordStstus({
          Id: id,
          Status: '50'
        }).then(res => {
          if (res.success === true) {
            this.$message({ type: 'success', message: this.$t('common.prompt.success.updateExpStatus') });
          } else {
            this.$message({ type: 'error', message: msg });
          }

          // 检查实验任务队列
          CheckExperimentQueue().then((res) => {
            if (res.success === false) {
              this.$message({ type: 'error', message: res.msg });
            }
          });

          this.init();
        });
      });
    },
    // 更改实验任务顺序
    async updateSort(tableData) {
      let tableSortData = [];
      tableData.forEach((value, index) => {
        if (value.status === this.$t('common.label.inQueue')) {
          tableSortData.push({
            Id: value.id,
            Value: value.sort.toString()
          });
        }
      });
      //console.log(tableSortData);

      UpdateExperimentRecordSort({ SetValueData: tableSortData }).then(res => {
        if (res.success === true) {
          this.$message({ type: 'success', message: this.$t('common.prompt.success.submit') });
        } else {
          this.$message({ type: 'error', message: msg });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 顶部按钮绝对定位
.formbtn { text-align: right; }
// 数据表格区样式
.show-result { margin-top: 1%; }
/* 操作项开关样式 */
::v-deep .switch .el-switch__label { position: absolute; display: none; color: #fff; }
/* 打开时文字位置设置 */
::v-deep .switch .el-switch__label--right { z-index: 1; right: 5px; }
/* 关闭时文字位置设置 */
::v-deep .switch .el-switch__label--left { z-index: 1; left: 8px; }
/* 显示文字 */
::v-deep .switch .el-switch__label.is-active { display: block; }
::v-deep .switch.el-switch .el-switch__core,
::v-deep .el-switch .el-switch__label { width: 60px !important; }
/* 表格隔行换色样式 */
::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td { background-color: #F2F2F2; }
/* 表格数据行高 */
::v-deep .el-table td { padding: 8px 0px; }
/* 表头背景色样式 */
::v-deep .el-table th{ background-color: #DBEDEF !important; }
/* 表头数据行内线样式 */
::v-deep .el-table td,.building-top .el-table th.is-leaf { border-bottom: 0px; }
/* 自定义提示框样式 */
.dialog_diy {
  ::v-deep .el-dialog__wrapper {
    .el-dialog {
      .el-dialog__body { padding: 0px; }
      .el-dialog__header { padding: 0px; }
      .el-dialog__headerbtn { top: 5px; right: 5px; padding-top: 10px; }
      .el-dialog__headerbtn .el-dialog__close { color: #fff; height: 30px; width: 35px; }
      .el-dialog__headerbtn .el-dialog__close:hover { color: gray; }
    }
  }
}
// 区域标题样式
.titie-bar {
  width: 4px;
  height: 32px;
  border-radius: 2px;
  background-color: rgba(61, 171, 175, 1);
  margin: 5px 0 5px 0;
}
.titie-bar span {
  color: #0A0A0A;
  width: 80px;
  font-size: 22px;
  line-height: 32px;
  white-space: nowrap;
  overflow-wrap: break-word;
  margin-left: 15px;
}

// 设备状态区域样式
.device-status-panal {
  height: 400px;
  border-radius: 8px;
  box-shadow: 0px 2px 6px 0px rgba(39, 122, 160, 0.09);
  background-size: contain;
  background-position: center center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}
.device-status-panal-bg {
  background-image: url(../../../assets/icon/automation_experiment/task_overview/device_status_bg.png);
}

// 实景监控按钮样式
.monitor-btn {
  width: 140px;
  height: 40px;
  background-color: rgba(61, 171, 175, 1);
  border: 1px solid rgba(255, 255, 255, 1);
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
  border-radius: 0px 8px 0px 16px;
  text-align: right;
  margin-top: -22px;
  margin-left: 35vw;
  margin-right: auto;
  display: flex;
  flex-direction: row;

  img {
    width: 24px;
    height: 24px;
    margin: 9px 0 0 24px;
  }

  span {
    width: 64px;
    height: 22px;
    color: rgba(255, 255, 255, 1);
    font-size: 16px;
    font-weight: 500;
    text-align: left;
    white-space: nowrap;
    overflow-wrap: break-word;
    line-height: 22px;
    margin: 9px 24px 0 0;
  }
}

// 统计区域样式
.statistics-panal {
  border-radius: 8px;
  //box-shadow: 0px 2px 6px 0px rgba(39, 122, 160, 0.09);
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}
.statistics-panal-bg-1 {
  background-image: url(../../../assets/icon/automation_experiment/task_overview/panal_bg_1.png);
}
.statistics-panal-bg-2 {
  background-image: url(../../../assets/icon/automation_experiment/task_overview/panal_bg_2.png);
}

.status-panal {
  height: 100px;
  border-radius: 8px;
  //box-shadow: 0px 2px 6px 0px rgba(39, 122, 160, 0.09);
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}
.status-titie {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background-color: rgba(61, 171, 175, 1);
  margin: -3px 0 0 5px;
  display: flex;
  flex-direction: column;

  span {
    color: #0A0A0A;
    font-size: 18px;
    white-space: nowrap;
    overflow-wrap: break-word;
    margin-top: -3px;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
  }
}
.status-value {
  text-align: center;
  margin-top: 5%;
  display: flex;
  flex-direction: column;

  span {
    color: rgba(1, 107, 110, 1);
    font-size: 28px;
    white-space: nowrap;
    overflow-wrap: break-word;
    display: flex;
    flex-direction: column;
  }
}

// 设备工作统计区域样式
.work-statistics-panal {
  text-align: left;
  font-weight: 500;
  white-space: nowrap;
  overflow-wrap: break-word;

  .title {
    color: rgba(51, 51, 51, 1);
    width: 200px;
    height: 28px;
    font-size: 20px;
    line-height: 80px;
  }
  .content{
    color: rgba(63, 171, 175, 1);
    font-size: 40px;
    font-weight: 500;
    line-height: 110px;

    span:nth-of-type(2),
    span:nth-of-type(4),
    span:nth-of-type(6) {
      font-size: 24px;
    }
  }
}
</style>
